package net.bat.service;

import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.bat.pt.BObj;
import net.cs.um.UMService;
/**
 * 默认的handle服务
 * @author chen4w
 *
 */
public class HDDefault implements IHandle {
	//分页获取数据,支持联合查询
	public static final char METHOD_GET ='G';
	//保存多行数据,支持多表保存
	public static final char METHOD_PUT ='P';
	//获得记录总数
	public static final char METHOD_COUNT = 'C';
	//获得用于新增的母对象
	public static final char METHOD_GETDEFAULT='D';
	//获得服务器时间
	public static final char METHOD_SVRTIME='T';
	//distinct查询,用于下拉框
	public static final char METHOD_DISTINCT='S';
	//每页最大行数
	private int pageSizeMax;

	private HDUtil util;

	public HDUtil getUtil() {
		return util;
	}


	public void setUtil(HDUtil util) {
		this.util = util;
	}


	public int getPageSizeMax() {
		return pageSizeMax;
	}


	public void setPageSizeMax(int pageSizeMax) {
		this.pageSizeMax = pageSizeMax;
	}

	public int count(HashMap<String,Object> req) throws Exception{
		String hql =(String)req.get("hql");
		return util.getDao().getCountByQuery(hql,null);
	}
	public List distinct(HashMap<String,Object> req) throws Exception{
		String hql =(String)req.get("hql");
		return util.getDao().find(hql);
	}

	@SuppressWarnings("unchecked")
	public BObj[] get(HashMap<String,Object> req) throws Exception {
		String hql =(String)req.get("hql");
		Integer start = (Integer)req.get("start");
		Integer rownum = (Integer)req.get("rownum");
		Integer readonly = (Integer)req.get("readonly");
		int int_start = start==null?0:start;
		int int_rownum = rownum==null?20:rownum;
		if(int_rownum>pageSizeMax) {
			int_rownum=pageSizeMax;
		}
		List ls = util.getDao().get(hql, int_start,	int_rownum);
		String[] cns= (String[])req.get("cns");
		String[][] pss = (String[][])req.get("pss");
		int len = ls.size();
		BObj[] rt;
		int pos;
		if(readonly==null){
			rt = new BObj[len+1];
			rt[0] = util.getDefaultObj(req);
			pos=1;
		}
		else{
			rt = new BObj[len];
			pos=0;
		}
		for(int i=0; i<len; i++){
			BObj ro = new BObj();
			ro.setAction(BObj.ACTION_ORIG);
			ro.setCns(cns);
			if(cns.length>1){
				util.getItemValue(ro,(Object[])ls.get(i),pss);
			}else{
				util.getItemValue(ro,ls.get(i),pss[0],"");
			}
			rt[i+pos]=ro;
		}
		return rt;
	}
	
	@Override
	public Object handle(char method, HashMap<String, Object> rm,
			HttpServletRequest request) throws Exception {
		// TODO Auto-generated method stub
		switch(method){
		case METHOD_DISTINCT:
			return distinct(rm);
		case METHOD_COUNT:
			return count(rm);
		case METHOD_GET:
			return get(rm);
		case METHOD_PUT:
			String[]cns = (String[])rm.get("cns");
			String[][] pss = (String[][])rm.get("pss");
			BObj[] objs = (BObj[])rm.get("objs");
			return util.putItemValue(objs, cns, pss,UMService.getUserBySession(request));
		}
		return null;
	}

}
